<?php
/*
 * @@Copyright (C), 2021-2022: 恒盛时代
 * @Author: zhouzhou
 * @Date: 2021/11/24
 * @Description: 群组禁言管理
 */

namespace App\Models;


use App\Http\Controllers\WebApi\Business\ConfigBusiness;
use App\Services\Configs\DefaultService;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterval;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Services\Huanxin\GroupServices;
use App\Services\RongCloud\GroupService;
use App\Services\Netease\GroupServices as NetGroupServices;


class ImGroupBanned extends BaseModel
{
    use SoftDeletes;
    protected $table = 'im_group_banned';

    /**
     * 关联群组表
     */
    public function group()
    {
        return $this->belongsTo(ImGroup::class, 'im_gid', 'im_gid');
    }


    /**
     * 关联用户表
     */
    public function user()
    {
        return $this->belongsTo(ImUsers::class, 'user_id', 'id');
    }

    /**
     * @desc 批量添加禁言的用户
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function addManyBanned($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroup['user_id'] != $userId)
        {
            return ['code' => 1, 'msg' => '权限不足'];
        }

        $member = $input['member_id'];
        $memberList = explode(",",$member);

        $ImGroupUser = new ImGroupUser();
        $ImGroupUser = $ImGroupUser->where(['im_gid' => $input['im_gid']])->whereIn('user_id', $memberList)->get();
        if (!$ImGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;
        switch($optionValue)
        {
            case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                $groupServices= new GroupServices();
                $groupServiceInfo = $groupServices->addGroupsMute($input['im_gid'], $memberList, (time()+$input['mute_duration']) * 1000);
                break;
            case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                $groupServices= new GroupService();
                $groupServiceInfo = $groupServices->addGag($memberList, $input['im_gid'], $input['mute_duration']/60);
                break;
            case ($optionValue == DefaultService::NETEASE_IM):  // 网易
                $groupServices= new NetGroupServices();
                foreach ($memberList as $key =>&$val)
                {
                    $groupServiceInfo = $groupServices->muteTlistGroup($input['im_gid'],$userId, $val,1 );
                }
                break;
        }

        if ($groupServiceInfo['code'] != 200)
        {
            return ['code' => 1, 'msg' => '禁言失败'];
        }

        // 批量插入禁言表
        $this->addMoreBanned($member, $input['im_gid'], $input['mute_duration']);

        $ImGroupUser = new ImGroupUser();
        $ImGroupUser->where(['im_gid' => $input['im_gid']])->whereIn('user_id', $memberList)->update(["status" => 3, "updated_at" => time()]);

        return ['code' => 0, 'id' => $this->id, 'msg' => '禁言成功'];
    }

    /**
     * @desc 新增多个禁言用户
     * @param string $member 逗号隔开的用户id
     * @param string $imGid 群组id
     * @param int $secondTime 禁言的秒钟
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/24 14:55
     */
    public function addMoreBanned($member, $imGid, $secondTime)
    {
        $memberList = explode(",",$member );
        $groupUser = [];
        foreach ($memberList as $key =>$val)
        {
            $groupUser[$key]['im_gid'] = $imGid;
            $groupUser[$key]['user_id'] = $val;
            $groupUser[$key]['mute_duration'] = time() + $secondTime;
            $groupUser[$key]['created_at'] = time();
            $groupUser[$key]['updated_at'] = time();
        }

        return $this->insert($groupUser);
    }

    /**
     * @desc 批量解除禁言
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/24 14:58
     */
    public function freeManyBanned($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroup['user_id'] != $userId)
        {
            return ['code' => 1, 'msg' => '权限不足'];
        }

        $member = $input['member_id'];
        $memberList = explode(",",$member);

        $imGroupBlackUsers = $this->where(['im_gid' => $input['im_gid']])->whereIn('user_id', $memberList)->get();
        if (!$imGroupBlackUsers)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;
        switch($optionValue)
        {
            case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                $groupServices= new GroupServices();
                $groupServiceInfo = $groupServices->delGroupsMute($input['im_gid'], $member);
                break;
            case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                $groupServices= new GroupService();
                $groupServiceInfo = $groupServices->removeGag($memberList, $input['im_gid']);
                break;
            case ($optionValue == DefaultService::NETEASE_IM):  // 网易
                $groupServices= new NetGroupServices();
                foreach ($memberList as $key =>&$val)
                {
                    $groupServiceInfo = $groupServices->muteTlistGroup($input['im_gid'],$userId, $val,0);
                }
                break;
        }

        if ($groupServiceInfo['code'] != 200)
        {
            return ['code' => 1, 'msg' => '禁言失败'];
        }

        // 批量删除黑名单，更新status1，
        $this->where(['im_gid' => $input['im_gid']])->whereIn('user_id', $memberList)->delete();

        $ImGroupUser = new ImGroupUser();
        $ImGroupUser->where(['im_gid' => $input['im_gid']])->whereIn('user_id', $memberList)->update(["status" => 0, "updated_at" => time()]);

        return ['code' => 0, 'id' => $this->id, 'msg' => '解除成功'];
    }

    /**
     * @desc 群组禁言列表管理
     * @param string $imGid 群组环信id
     * @param int $userId 用户id
     * @param int $limit 每页默认10个
     * @param int $offset 从那条数据开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/23 16:50
     */
    public function bannedList($imGid, $userId = 0, $limit = 10, $offset = 0)
    {
        $list = $this->select('id', 'im_gid', 'user_id', 'mute_duration')->with(['group' => function($q){
            $q->select('im_gid','name','description','face');
        }])->with(['user' => function($q){
            $q->select('id','nickname','headimg');
        }])->where(['im_gid'=>$imGid])
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get()->map(function($val) use($userId){
                $diffTime = $val['mute_duration'] - time();
                $val['for_time'] = Sec2Time($diffTime);
                $val['banner_desc'] = "约{$val['for_time']}后解除禁言";

                return $val;
            });

        return $list;
    }

    /**
     * @desc 禁言跑脚本，解除禁言
     * @return array
     * @author zhouzhou
     * @time 2021/12/23 10:31
     */
    public function removeBanne()
    {
        $timeNow = time();
        $pageNum = 1;
        $code = true;
        $imGroupUseModel = new ImGroupUser();
        do{
            $pageSize = 100;
            $offset = ($pageNum - 1) * $pageSize;
            $list = $this->select('id', 'im_gid', 'user_id', 'mute_duration')
                ->where('mute_duration','<',$timeNow)
                ->orderBy('id', 'desc')
                ->limit($pageSize)
                ->offset($offset)
                ->get()->toArray();

            if(empty($list))
            {
                $code = false;
            }
            $pageNum++;
            foreach ($list as $key =>$item)
            {
                $imGroupUser = $imGroupUseModel->where(['im_gid' => $item['im_gid'],'user_id' => $item['user_id'], 'status'=>3])->first();
                if (!empty($imGroupUser))
                {
                    $imGroupUser->status = 0;
                    $imGroupUser->save();

                    $this->where(['im_gid' => $item['im_gid'],'user_id' => $item['user_id']])->delete();
                }
            }

        }while($code);
        return true;
    }


}
